package cn.sfrog.project.biz.admin.service.impl;

import cn.sfrog.common.core.domain.entity.SysUser;
import cn.sfrog.common.exception.ServiceException;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.project.biz.admin.domain.BizMessageConversation;
import cn.sfrog.project.biz.admin.domain.BizMessageLog;
import cn.sfrog.project.biz.admin.domain.vo.BizMessageConversationFormVO;
import cn.sfrog.project.biz.admin.domain.vo.BizMessageConversationQueryVO;
import cn.sfrog.project.biz.admin.domain.vo.BizMessageConversationVO;
import cn.sfrog.project.biz.admin.mapper.BizMessageConversationMapper;
import cn.sfrog.project.biz.admin.mapper.BizMessageLogMapper;
import cn.sfrog.project.biz.admin.service.IBizMessageConversationService;
import cn.sfrog.project.biz.web.vo.websocket.AppConversationQueryVO;
import cn.sfrog.project.biz.web.vo.websocket.AppConversationResultVO;
import cn.sfrog.project.biz.web.vo.websocket.AppKfUserVO;
import cn.sfrog.system.domain.vo.BizStatusChangeVO;
import cn.sfrog.system.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;


/**
 * 聊天会话Service业务层处理
 */
@Service
public class BizMessageConversationServiceImpl extends ServiceImpl<BizMessageConversationMapper, BizMessageConversation> implements IBizMessageConversationService {
    @Resource
    private BizMessageConversationMapper bizMessageConversationMapper;
    @Resource
    private BizMessageLogMapper bizMessageLogMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 查询聊天会话
     *
     * @param id 聊天会话主键
     * @return 聊天会话
     */
    @Override
    public BizMessageConversationVO selectBizMessageConversationById(Long id) {
        return bizMessageConversationMapper.selectBizMessageConversationById(id);
    }

    /**
     * 查询聊天会话列表
     *
     * @param query 聊天会话
     * @return 聊天会话
     */
    @Override
    public List<BizMessageConversationVO> selectBizMessageConversationList(BizMessageConversationQueryVO query) {
        return bizMessageConversationMapper.selectBizMessageConversationList(query);
    }

    /**
     * 新增聊天会话
     *
     * @param form 聊天会话
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean insertBizMessageConversation(BizMessageConversationFormVO form) {
        BizMessageConversation bizMessageConversation = new BizMessageConversation();
        BeanUtils.copyProperties(form, bizMessageConversation);
        bizMessageConversation.setCreateTime(new Date());
        bizMessageConversation.setCreateBy(SecurityUtils.getUsername());
        bizMessageConversation.setUpdateTime(new Date());
        bizMessageConversation.setUpdateBy(SecurityUtils.getUsername());
        return bizMessageConversation.insert();
    }

    /**
     * 修改聊天会话
     *
     * @param form 聊天会话
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateBizMessageConversation(BizMessageConversationFormVO form) {
        BizMessageConversation bizMessageConversation = new BizMessageConversation();
        BeanUtils.copyProperties(form, bizMessageConversation);
        bizMessageConversation.setUpdateTime(new Date());
        bizMessageConversation.setUpdateBy(SecurityUtils.getUsername());
        return bizMessageConversation.updateById();
    }

    /**
     * 批量删除聊天会话
     *
     * @param ids 需要删除的聊天会话主键
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean deleteBizMessageConversationByIds(Long[] ids) {
            return BizMessageConversation.DAO.delete(Wrappers.lambdaQuery(BizMessageConversation.class).in(BizMessageConversation::getId, (Object[]) ids));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean changeStatus(BizStatusChangeVO vo) {
       // return BizMessageConversation.DAO.update(Wrappers.lambdaUpdate(BizMessageConversation.class).in(BizMessageConversation::getId, (Object[]) vo.getIds()).set(BizMessageConversation::getStatus, vo.getStatus()));
        return true;
    }

    @Override
    public Integer selectUnReadCount() {

        return null;
    }

    @Override
    public List<AppConversationResultVO> selectAppConversationList(AppConversationQueryVO query) {
        List<AppConversationResultVO> conversationList = bizMessageConversationMapper.selectAppConversationList(query);
        for (AppConversationResultVO vo:conversationList) {
            if(query.getUserId().equals(vo.getSendUserId())){
                vo.setUnReadCount(vo.getSendUnreadCount());
            }else {
                vo.setUnReadCount(vo.getReceiveUnreadCount());
            }
            //查询最新的一条消息
            LambdaQueryWrapper<BizMessageLog> lambdaQueryWrapper = new LambdaQueryWrapper<BizMessageLog>()
                    .eq(BizMessageLog::getConversationId,vo.getId())
                    .orderByDesc(BizMessageLog::getCreateTime)
                    .last(" limit 1");
            BizMessageLog messageLog = bizMessageLogMapper.selectOne(lambdaQueryWrapper);
            if(StringUtils.isNotNull(messageLog)){
                vo.setLastMessage(messageLog.getContent());
                vo.setCreateTime(messageLog.getCreateTime());
                vo.setType(messageLog.getType());
            }
        }
        return conversationList;
    }

    @Override
    public AppKfUserVO selectKfUser() {
        AppKfUserVO appKfUserVO = new AppKfUserVO();
        //1.先查询所有的客服列表
        List<AppKfUserVO> userVOList =  bizMessageConversationMapper.selectAllKfUser();
        if(CollectionUtils.isEmpty(userVOList)){
            throw new ServiceException("暂未配置客服");
        }
        List<Long> userIdList = userVOList.stream().map(item -> item.getUserId()).collect(Collectors.toList());
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<BizMessageConversation> queryWrapper = new LambdaQueryWrapper<BizMessageConversation>()
                .eq(BizMessageConversation::getSendUserId,userId)
                .in(BizMessageConversation::getReceiveUserId,userIdList);
        List<BizMessageConversation> bizMessageConversations = BizMessageConversation.DAO.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(bizMessageConversations)){
            if(bizMessageConversations.size() > 1){
                throw new ServiceException("查询错误");
            }else {
                Long receiveUserId = bizMessageConversations.get(0).getReceiveUserId();
                if(receiveUserId !=null){
                    SysUser sysUser = sysUserMapper.selectUserById(receiveUserId);
                    if(sysUser !=null){
                        appKfUserVO.setUserId(receiveUserId);
                        appKfUserVO.setNickName(sysUser.getNickName());
                        appKfUserVO.setAvatar(sysUser.getAvatar());
                    }
                }
            }
        }else {
            //第一次聊 随机分配一个客服
            appKfUserVO = userVOList.get(new Random().nextInt(userIdList.size()));
        }
        return appKfUserVO;
    }
}
